import jwt
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed

from user.models import UserModels
from utils.myjwt import jwtweb

# 验证token
class MyAuthentication(BaseAuthentication):
    def authenticate(self, request):
        token = request.META.get('HTTP_AUTHORIZATION', None)
        # 验证token的合法性
        if token:
            tokendata = token.split(" ")[1]
            try:
                result = jwtweb.checktoken(tokendata)
                user = UserModels.objects.get(id=result.get("id"))
                return user, tokendata
            except jwt.ExpiredSignatureError:
                raise AuthenticationFailed("token过期")
            except jwt.InvalidTokenError:
                raise AuthenticationFailed("token无效")

